﻿﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Demo</title>
	<link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
	<style>
		body {
			background-color: #f2f2f2;
			padding: 20px;
		}

		.invoice-container {
			background-color: #fff;
			padding: 20px;
			border-radius: 5px;
			box-shadow: 0 0 10px rgba(0,0,0,0.1);
		}

		.form-title {
			margin-bottom: 20px;
			padding-bottom: 10px;
			border-bottom: 1px solid #eee;
			color: #333;
		}

		.form-table {
			width: 100%;
			margin-bottom: 15px;
		}

			.form-table td {
				padding: 10px 15px;
				vertical-align: top;
			}

		.form-actions {
			text-align: center;
			margin-top: 20px;
			padding-top: 20px;
			border-top: 1px solid #eee;
		}

		.layui-form-label {
			width: 100px;
		}

		.layui-input-block {
			margin-left: 130px;
		}

		.layui-form-item {
			margin-bottom: 15px;
		}

		.required:before {
			content: '*';
			color: red;
			margin-right: 4px;
		}

		/* 对话框样式 */
		.dialog-body {
			padding: 15px;
			overflow-y: auto;
			max-height: 70vh;
		}
		/* -------------------------- */
		.material-info-section {
			margin: 20px 0;
			border: 1px solid #ddd;
			padding: 15px;
			border-radius: 5px;
		}

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15px;
		}

		.material-table {
			width: 100%;
			border-collapse: collapse;
		}

			.material-table th, .material-table td {
				border: 1px solid #ddd;
				padding: 8px;
				text-align: center;
			}

			.material-table th {
				background-color: #f2f2f2;
			}

			.material-table input {
				width: 100%;
				box-sizing: border-box;
				padding: 5px;
			}

		.btn {
			padding: 5px 10px;
			cursor: pointer;
			border: none;
			border-radius: 3px;
		}

		.btn-primary {
			background-color: #4CAF50;
			color: white;
		}

		.btn-save {
			background-color: #2196F3;
			color: white;
			padding: 8px 15px;
		}

		.btn-delete {
			background-color: #f44336;
			color: white;
		}

		.modal {
			display: none;
			position: fixed;
			z-index: 1;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			overflow: auto;
			background-color: rgba(0,0,0,0.4);
		}

		.modal-content {
			background-color: #fefefe;
			margin: 5% auto;
			padding: 20px;
			border: 1px solid #888;
			width: 80%;
			max-width: 900px;
		}

		.modal-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-bottom: 10px;
			border-bottom: 1px solid #ddd;
		}

		.close {
			color: #aaa;
			font-size: 28px;
			font-weight: bold;
			cursor: pointer;
		}

		.search-bar {
			margin: 15px 0;
			display: flex;
		}

			.search-bar input {
				flex: 1;
				padding: 8px;
				margin-right: 10px;
			}

		.material-select-table {
			width: 100%;
			border-collapse: collapse;
		}

			.material-select-table th, .material-select-table td {
				border: 1px solid #ddd;
				padding: 8px;
				text-align: center;
			}

		.pagination {
			margin-top: 15px;
			text-align: right;
		}

			.pagination input {
				width: 50px;
				text-align: center;
				margin: 0 5px;
			}
	</style>
</head>
<body>

	<span class="layui-breadcrumb">
		<a href="GetProcurements">采购发票列表</a>
	</span>

	<form class="layui-form" action="" id="baseStoreForm">
		<div class="layui-input-inline">
			<label class="layui-input-inline" style="width:auto">单据编码</label>
			<div class="layui-input-inline">
				<input type="text" name="documentcode" class="layui-input">
			</div>
			<label class="layui-input-inline" style="width:auto">发票号码</label>
			<div class="layui-input-inline">
				<input type="text" name="invoicenumber" class="layui-input">
			</div>
			<div class="layui-input-inline">
				<div class="layui-inline">
					<label class="layui-input-inline" style="width:auto">日期范围</label>
					<div class="layui-inline" id="ID-laydate-range">
						<div class="layui-input-inline">
							<input type="text" autocomplete="off" name="begindate" class="layui-input" id="begindate" placeholder="开始日期">
						</div>
						<div class="layui-form-mid">-</div>
						<div class="layui-input-inline">
							<input type="text" autocomplete="off" name="enddate" class="layui-input" id="enddate" placeholder="结束日期">
						</div>
					</div>
				</div>
			</div>
			<button class="layui-btn" lay-submit lay-filter="search">查询</button>
			<button type="reset" class="layui-btn layui-btn-primary">重置</button>
			<button type="button" class="layui-btn layui-btn-normal" id="addBtn">新增</button>
		</div>
	</form>
	
	<table class="layui-hide" id="table_row"></table>
	<!-- 新增对话框 - 隐藏的表单 -->
	<div id="addDialog" style="display: none;">
		<div class="dialog-body">
			<div class="layui-container invoice-container">
				<h2 class="form-title">新增采购发票</h2>

				<form class="layui-form" id="purchaseInvoiceForm">
					<table class="form-table">
						<tr>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label required">单据编码：</label>
									<div class="layui-input-block">
										<input type="text" name="documentCode" placeholder="请输入单据编码" autocomplete="off" class="layui-input">
										<button type="button" class="layui-btn layui-btn-primary" id="randomGenerate" style="margin-left: 10px;">随机生成</button>
									</div>
								</div>
							</td>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label required">业务类型：</label>
									<div class="layui-input-block">
										 <select name="documentid" lay-verify="required"> 
										  	<option value="">请选择业务类型</option> 
										  	<option value="1" selected>零部件发票</option> 
										  	<option value="2">原材料发票</option> 
										  	<option value="3">服务类发票</option> 
										  </select> 
										
									</div>
								</div>
							</td>
						</tr>
						<tr>
							<td>
								<div class="layui-col-md6">
									<label class="layui-form-label">供应商</label>
									<select name="supid" id="supidSel" lay-search>
										<option value="">请选择供应商</option>
									</select>
								</div>
							</td>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label required">开票日期：</label>
									<div class="layui-input-block">
										<input type="text" name="invoiceDate" id="dialogInvoiceDate" autocomplete="off" class="layui-input" lay-verify="required">
									</div>
								</div>
							</td>
						</tr>
						<tr>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label required">单据日期：</label>
									<div class="layui-input-block">
										<input type="text" name="documentTime" id="dialogDocumentTime" autocomplete="off" class="layui-input" lay-verify="required">
									</div>
								</div>
							</td>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">操作员：</label>
									<div class="layui-input-block">
										<input type="text" name="operator" value="njrsun" autocomplete="off" class="layui-input" readonly>
									</div>
								</div>
							</td>
						</tr>
						<tr>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">税号：</label>
									<div class="layui-input-block">
										<input type="text" name="taxNumber" placeholder="请输入税号" autocomplete="off" class="layui-input">
									</div>
								</div>
							</td>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">红字蓝字：</label>
									<div class="layui-input-block">
										<select name="redandblue">
											<option value="1" selected>蓝字</option>
											<option value="2">红字</option>
										</select>
									</div>
								</div>
							</td>
						</tr>
						<tr>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">单据状态：</label>
									<div class="layui-input-block">
										<select class="layui-readonly" name="documentStuct">
											<option value="true" selected>开立</option>
											<option value="false">审核</option>
										</select>
									</div>
								</div>
							</td>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">审核员：</label>
									<div class="layui-input-block">
										<input type="text" name="auditor" autocomplete="off" class="layui-input">
									</div>
								</div>
							</td>
						</tr>
						<tr>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">发票类型：</label>
									<div class="layui-input-block">
										<select name="invoiceType">
											<option value="">请选择发票类型</option>
											<option value="1">增值税专用发票</option>
											<option value="2">普通发票</option>
											<option value="3">电子发票</option>
										</select>
									</div>
								</div>
							</td>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">发票金额：</label>
									<div class="layui-input-block">
										<input type="text" name="invoiceAmount" placeholder="0.00" autocomplete="off" class="layui-input">
									</div>
								</div>
							</td>
						</tr>
						<tr>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">业务状态：</label>
									<div class="layui-input-block">
										<select name="businessStuct">
											<option value="1" selected>正常</option>
											<option value="2">异常</option>
											<option value="3">待处理</option>
										</select>
									</div>
								</div>
							</td>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label required">审核日期：</label>
									<div class="layui-input-block">
										<input type="text" name="auditDate" id="dialogAuditDate" value="2025-03-28" autocomplete="off" class="layui-input">
									</div>
								</div>
							</td>
						</tr>
						<tr>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">发票代码：</label>
									<div class="layui-input-block">
										<input type="text" name="invoiceCode" placeholder="请输入发票代码" autocomplete="off" class="layui-input">
									</div>
								</div>
							</td>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">税额：</label>
									<div class="layui-input-block">
										<input type="text" name="taxAmount" placeholder="0.00" autocomplete="off" class="layui-input">
									</div>
								</div>
							</td>
						</tr>
						<tr>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">发票号码：</label>
									<div class="layui-input-block">
										<input type="text" name="invoiceNumber" placeholder="请输入发票号码" autocomplete="off" class="layui-input">
									</div>
								</div>
							</td>
							<td>
								<div class="layui-form-item">
									<label class="layui-form-label">价税合计：</label>
									<div class="layui-input-block">
										<input type="text" name="totalIncludingTax" placeholder="0.00" autocomplete="off" class="layui-input">
									</div>
								</div>
							</td>
						</tr>
					</table>

					<div class="form-actions">
						<button id="save-btn" class="layui-btn" lay-submit lay-filter="submitAdd">
							<i class="layui-icon">&#xe608;</i> 保存
						</button>
						<button type="button" class="layui-btn layui-btn-normal" id="dialogCancelBtn">
							<i class="layui-icon">&#x1006;</i> 取消
						</button>
						<button type="button" class="layui-btn layui-btn-primary" id="auditBtn">
							<i class="layui-icon">&#xe605;</i> 审核
						</button>
						<button type="button" class="layui-btn layui-btn-danger" id="antiAuditBtn">
							<i class="layui-icon">&#x1007;</i> 反审核
						</button>
						<button type="button" class="layui-btn layui-btn-default" id="collapseBtn">
							<i class="layui-icon">&#xe61a;</i> 收起
						</button>
					</div>

					@* ------------------------------------ *@

				</form>
				@* ------- *@

				<div class="material-info-section">
					<div class="section-header">
						<h3>物料信息</h3>
						<button id="add-material-btn" class="btn btn-primary">新增物料</button>
					</div>

					<table class="material-table">
						<thead>
							<tr>
								<th width="10">序号</th>
								<th width="15">采购订单号</th>
								<th width="15">仓库</th>
								<th width="15">入库单号</th>
								<th width="12%">物料编码</th>
								<th width="10">物料名称</th>
								<th width="12">型号规格</th>
								<th width="8">主计量</th>
								<th width="10">数量</th>
								<th width="10">单价</th>
								<th width="10">金额</th>
								<th width="10">税率</th>
								@* <th width="10">税额</th> *@
								<th width="8">操作</th>
							</tr>
						</thead>
						<tbody id="material-tbody">
							<!-- 动态生成的行会在这里 -->
						</tbody>
					</table>

					<!-- 物料选择模态框 -->
					<div id="material-modal" class="modal">
						<div class="modal-content">
							<div class="modal-header">
								<h4>选择物料</h4>
								<span class="close">&times;</span>
							</div>
							<div class="modal-body">
								<div class="search-bar">
									<input type="text" id="material-search" placeholder="输入物料编码或名称搜索">
									<button id="search-btn">搜索</button>
								</div>
								<table class="material-select-table">
									<thead>
										<tr>
											<th>物料编码</th>
											<th>物料名称</th>
											<th>型号规格</th>
											<th>主计量</th>
											<th>操作</th>
										</tr>
									</thead>
									<tbody id="material-select-tbody">
										<!-- 物料选择数据会在这里 -->
									</tbody>
								</table>
								<div class="pagination">
									<span>共52条</span>
									<span>100条/页</span>
									<span>前往</span>
									<input type="number" value="1" min="1">
									<span>页</span>
								</div>
							</div>
						</div>
					</div>
				</div>
				<!--<button id="save-btn" class="btn btn-save">保存</button>-->
			</div>
		</div>
	</div>
	<script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
	<script>
			layui.use(['table', 'jquery', 'layer', 'form', 'laydate'], function () {
			var table = layui.table;
			var $ = layui.jquery;
			var layer = layui.layer;
			var form = layui.form;
			var laydate = layui.laydate;

			// 初始化日期范围
			laydate.render({
				elem: '#begindate'
			});

			laydate.render({
				elem: '#enddate'
			});
			
			//初始化表格
			table.render({
				//url: '/static/json/2/table/demo1.json', // 此处为静态模拟数据，实际使用时需换成真实接口
				toolbar: '#toolbarDemo',
				defaultToolbar: ['filter', 'exports', 'print', { // 右上角工具图标
					  title: '提示',
					  layEvent: 'LAYTABLE_TIPS',
					  icon: 'layui-icon-tips',
					  onClick: function(obj) { // 2.9.12+
						layer.alert('自定义工具栏图标按钮');
					  }
				}],
				height: 'full-35', // 最大高度减去其他容器已占有的高度差
				css: [ // 重设当前表格样式
				  '.layui-table-tool-temp{padding-right: 145px;}'
				].join(''),
				cellMinWidth: 80,
				totalRow: true, // 开启合计行
				elem: '#table_row',
				id: 'BaseStoretable',
				height: '450',				
				cols: [[
					{ field: 'peid', width: 80, sort: true, fixed: 'left', title: 'id' },
					{ field: 'documentCode', width: 130, title: '单据编码' },
					{
						field: 'invoiceDate',
						width: 160,
						title: '单据日期',
						templet: function (d) {
							return d.invoiceDate ? layui.util.toDateString(d.invoiceDate, 'yyyy-MM-dd') : '';
						}
					},
					{ field: 'documentStuct', width: 130, title: '单据状态',
						templet:function(d){
							if (d.documentStuct == true) {
								return '开立';
							} else if (d.documentStuct == false) {
								return '审核';
							} else {
								return d.documentStuct;
							}
						}
					},
					{ field: 'businessStuct', width: 130, title: '业务类型',
					  templet:function(d){
							if (d.businessStuct == 1) {
								return '正常';
							} else if (d.businessStuct == 2) {
								return '挂起';
							} else if (d.businessStuct == 3) {
								return '手工关闭';
							} else if (d.businessStuct == 4) {
								return '系统关闭';
							}else {
								return d.businessStuct;
							}
					  }
					},
					{ field: 'supplierName', width: 100, title: '厂家名称' },
					{ field: 'invoiceCode', width: 100, title: '发票号码' },
					{ field: 'invoiceAmount', width: 100, title: '发票金额' },
					{ field: 'taxLv', width: 100, title: '税率' },
					{ field: 'taxAmount', width: 100, title: '税额' },
					{ field: 'financialStatus', width: 100, title: '财务状态',
					  templet:function(d) {
						  if(d.financialStatus==1){
							return '录入';
						  }else if(d.financialStatus==2){
							return '审核中';
						  }else{
							return '完成';
						  }
					   }
					},
					{fixed:'right',title:'操作',width:200,toolbar:'#operationBar'},
				]],
			});
			

			// 监听工具条事件
			table.on('tool(BaseStoretable)', function(obj){ // 注意：table_row 是表格的elem属性值
				var data = obj.data; // 获取当前行数据
				var layEvent = obj.event; // 获取lay-event对应的值

				if(layEvent === 'edit'){ // 编辑操作
					// 跳转到编辑页面，并传递当前行数据
					console.log(111)
					editData(data);
				} else if(layEvent === 'del'){ // 删除操作
					layer.confirm('确定删除此记录吗？', function(index){
						// 执行删除操作
						obj.del(); // 删除对应行（DOM结构）
						layer.close(index);
					});
				} else if(layEvent === 'lookit'){ // 查看操作
					LookData(data);
				}
			});

			// 编辑数据函数
			function editData(data) {
				//console.log(data)
				// 将数据转换为JSON字符串
				var dataStr = JSON.stringify(data);
				// 使用localStorage或sessionStorage临时存储数据
				sessionStorage.setItem('editData', dataStr);
				// 跳转到编辑页面
				window.location.href = 'ProcurementsAdd'; // 替换为你的编辑页面B的实际路径
			}
			// 查看数据函数
			function LookData(data) {
				//console.log(data)
				// 将数据转换为JSON字符串
				var dataStr = JSON.stringify(data);
				// 使用localStorage或sessionStorage临时存储数据
				sessionStorage.setItem('LookData', dataStr);
				// 跳转到编辑页面
				window.location.href = 'LookProcurements'; // 替换为你的编辑页面B的实际路径
			}




			// 新增按钮点击事件打开对话框
			$('#addBtn').on('click', function () {
				layer.open({
					type: 1,
					title: '新增采购发票',
					area: ['1200px', '650px'], // 调整对话框大小以适应表单
					content: $('#addDialog'),
					success: function(layero, index) {
						// 初始化对话框内的日期控件
						laydate.render({
							elem: '#dialogInvoiceDate',
							value: new Date(),
							trigger: 'click'
						});

						// 重置表单
						$('#purchaseInvoiceForm')[0].reset();
						// 重新渲染表单
						form.render();

						// 设置默认值
						//$('#dialogDocumentTime').val(new Date().toISOString().split('T')[0]);
					}
				});
			});

			// 对话框取消按钮
			$('#dialogCancelBtn').on('click', function() {
				layer.closeAll();
			});
			//----------------------------------------------------------------
			//绑定供应商
			initSelectData();
			function initSelectData(){
			$.ajax({
					type: 'GET',
					//url: 'http://localhost:5234/api/Customermanage/GetMaterial',  // 替换为实际接口地址
					url: "@ViewBag.BaseUrl/T7/Customermanage/GetMaterial",
					dataType: 'json',
					success: function (res) {
						console.log('当前是:'+res);
						if (res.code === 210) {
							var options = '';
							// 遍历后端返回数据
							$.each(res.data, function (index, item) {
								options += '<option value="' + item.supid + '">' + item.supplierName + '</option>';
							});
							// 添加到下拉框
							$('#supidSel').append(options);
							// 渲染下拉框
							form.render('select');
						} else {
							layer.msg('获取数据失败：' + res.msg);
						}
					},
					error: function (xhr, status, error) {
						layer.msg('网络请求失败，请检查网络！');
						console.error(error);
					}
				});
			}

			// 随机生成按钮点击事件
			document.getElementById('randomGenerate').addEventListener('click', function() {
				// 生成8位随机数
				var randomNum = Math.floor(10000000 + Math.random() * 90000000);
				// 设置到单据编码输入框
				document.getElementsByName('documentCode')[0].value = randomNum;
			});

			// 监听发票金额和税额的输入变化
			document.querySelector('input[name="invoiceAmount"]').addEventListener('input', calculateTotal);
			document.querySelector('input[name="taxAmount"]').addEventListener('input', calculateTotal);
			function calculateTotal() {
				// 获取发票金额和税额的值（若为空则默认为0）
				const invoiceAmount = parseFloat(document.querySelector('input[name="invoiceAmount"]').value) || 0;
				const taxAmount = parseFloat(document.querySelector('input[name="taxAmount"]').value) || 0;

				// 计算价税合计（发票金额 + 税额）
				const total = invoiceAmount + taxAmount;

				// 将结果显示在价税合计输入框中，保留2位小数
				document.querySelector('input[name="totalIncludingTax"]').value = total.toFixed(2);
			}
			
			// 保存按钮点击事件
			form.on('submit(submitAdd)', function(data) {
				console.log(data);
				var fromData = data.field;
				var postData = {
					documentCode: fromData.documentCode,
					documentTime: fromData.documentTime,
					documentStuct: fromData.documentStuct ==="true",
					businessStuct: fromData.businessStuct,    
					documentid: fromData.documentid,
					auditor: fromData.auditor,
					operator: fromData.operator,
					auditDate: fromData.auditDate,
					supid: fromData.supid||1,
					taxNumber: fromData.taxNumber,
					invoiceType: fromData.invoiceType,
					invoiceCode: fromData.invoiceCode,
					invoiceNumber: fromData.invoiceNumber,
					invoiceDate: fromData.invoiceDate,
					redandblue: fromData.redandblue,
					invoiceAmount: fromData.invoiceAmount,
					taxAmount: fromData.taxAmount,
					totalIncludingTax: fromData.totalIncludingTax,
					financialStatus: fromData.financialStatus,
					taxLv:fromData.taxLv,
					material_code:fromData.material_code,
					orderNumber: "", // 主单据级别的字段
					warehouse: "",
					receiptNumber: "", // 注意拼写
					materialCode: "",
					materialName: "",
					specification: "",
					unit: "",
					pcount: 0,
					price: 0,
					materialtab:[]
				};

				const rows = document.querySelectorAll('#material-tbody tr'); // 修正选择器
				console.log("获取到的行数据：", rows);

				// 3. 遍历每一行数据
				rows.forEach(row => {
					postData.materialtab.push({
						material_id: 0,
						category_id: 0,
						materialCode: row.querySelector('.material-code').value || "0",
						material_name: row.querySelector('.material-name').value || "",
						model_specification: "",
						drawing_number: "",
						specification_desc: row.querySelector('.specification').value || "",
						unit: row.querySelector('.unit').value || "", // 添加unit字段
						unit_of_measurement_id: 0,
						supply_method_id: 0,
						allow_negative_stock: true,
						keep_material_name: true,
						updateTime: new Date().toISOString(),
						orderNumber: row.querySelector('.order-number').value || "", // 添加orderNumber
						warehouse: row.querySelector('.warehouse').value || "", // 添加warehouse
						receiptNumber : row.querySelector('.receipt-number').value,
						label: true,
						pcount: parseFloat(row.querySelector('.pcount').value) || 0,
						price: parseFloat(row.querySelector('.price').value) || 0,

						materialName : row.querySelector('.material-name').value||"",
						specification : row.querySelector('.specification').value||""
					});

				});

				// 4. 打印数据并提示（实际应发送到后端）
				console.log('保存的物料数据：', postData.materialtab);
				layer.msg('数据已收集，请检查控制台输出', { icon: 1 });

				var loadIndex = layer.load(2);

				$.ajax({
					//url: 'http://localhost:5090/api/PurchaseInvoices/AddPurchase',
					url: "@ViewBag.BaseUrl/T8/PurchaseInvoices/AddPurchase",
					type: 'POST',
					contentType: 'application/json',
					data: JSON.stringify(postData),
					dataType: 'json',
					success: function(res) {
						layer.close(loadIndex);
						if (res.code == 212) {
							layer.msg(res.msg, {icon: 1});
						} else {
							layer.msg(res.msg || '新增失败', {icon: 2});
						}
					},
						error: function(xhr, status, error) {
						layer.close(loadIndex);
						var errorMsg = '请求失败: ' + error;
						if(xhr.responseJSON && xhr.responseJSON.message) {
							errorMsg += ' - ' + xhr.responseJSON.message;
						}
						layer.msg(errorMsg, {icon: 2});
						console.error('AJAX请求失败:', xhr.responseText);
						console.log('发送的数据:', JSON.stringify(postData, null, 2));
					}
				});

				return false;
			});
			// 审核按钮点击事件
			$('#auditBtn').on('click', function(){
				var documentCode = $('input[name="documentCode"]').val();
				if(!documentCode) {
					layer.msg('请先填写单据编码', {icon: 2});
					return;
				}

				// 调用审核接口
				updateOrderStatus(documentCode, 'audit');
			});
			// 简化版的updateOrderStatus函数
			function updateOrderStatus(documentCode, action) {
				var loadIndex = layer.load(2);
				var peid = action === 'audit' ? 1 : 0;

				$.ajax({
					//url: 'http://localhost:5000/api/PurchaseInvoices/EditPurchaseorderStatus',
					url: "@ViewBag.BaseUrl/T8/PurchaseInvoices/EditPurchaseorderStatus",
					type: 'POST',
					contentType: 'application/json',
					data: JSON.stringify({ peid: peid }),
					dataType: 'json',
					success: function(res) {
						layer.close(loadIndex);
						if (res.code == 200) {
							layer.msg('操作成功', {icon: 1});
							updateStatusDisplay(action);
						} else {
							layer.msg('操作失败: ' + (res.msg || ''), {icon: 2});
						}
					},
					error: function(xhr, status, error) {
						layer.close(loadIndex);
						layer.msg('请求失败: ' + error, {icon: 2});
					}
				});
			}

			//渲染列表
			function loadRoleData() {
				layer.load(2);
				var params = {
					documentcode: $('[name="documentcode"]').val()||0,
					invoicenumber: $('[name="invoicenumber"]').val(),
					begindate: $('[name="begindate"]').val(),
					enddate: $('[name="enddate"]').val()
				}
				$.ajax({
					//url: 'http://localhost:5234/api/PurchaseInvoice/GetPurchaseInvoice',					
					url: "@ViewBag.BaseUrl/T7/PurchaseInvoice/GetPurchaseInvoice",
					data: params,
					type: 'get',
					dataType: 'json',
					success: function (res) {
						console.log(res.data);
						layer.closeAll('loading');
						if (res.code === 210) {
							table.reload('BaseStoretable', {
								data: res.data,
							});
						}
						else {
							layer.msg('获取数据失败: ' + (res.message || '未知错误'), { icon: 2 });
						}
					},
					error: function (xhr, status, error) {
						layer.closeAll('loading');
						layer.msg('请求失败: ' + error, { icon: 2 });
						console.error('Ajax请求失败:', xhr.responseText);
					}
				});
			}

			// 搜索按钮点击事件
			form.on('submit(search)', function (data) {
				loadRoleData();
				return false; // 阻止表单跳转
			});

			// 页面加载完成后获取数据
			loadRoleData();
		});
	</script>
	<!-- 操作列按钮模板 -->
	<script type="text/html" id="operationBar">
		<a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
		<a class="layui-btn layui-btn-success layui-btn-xs" lay-event="lookit">查看</a>
	</script>
	<script>
		//---111

				document.addEventListener('DOMContentLoaded', function(){
				let rowCount = 0;
				const modal = document.getElementById('material-modal');
				//const currentSelectingRow = { index: null, element: null };

				// 新增物料行
				document.getElementById('add-material-btn').addEventListener('click', function() {
					rowCount++;
					const tbody = document.getElementById('material-tbody');
					const newRow = document.createElement('tr');
					newRow.dataset.index = rowCount;

					newRow.innerHTML = `
						<td>${rowCount}</td>
						<td><input type="text" class="order-number" value=""></td>
						<td><input type="text" class="warehouse" value=""></td>
						<td><input type="text" class="receipt-number" value=""></td>
						<td>
							<div class="material-code-select">
								<input type="text" class="material-code" placeholder="点击选择">
								<button class="btn-select">选择</button>
							</div>
						</td>
						<td><input type="text" class="material-name" readonly></td>
						<td><input type="text" class="specification" readonly></td>
						<td><input type="text" class="unit" readonly></td>
						<td><input type="number" class="pcount" min="0" step="0.01"></td>
						<td><input type="number" class="price" min="0" step="0.01"></td>
						<td><input type="number" class="howmany" min="0" step="0.01"></td>
						<td><input type="number" class="taxLv" min="0" step="0.01"></td>
						
						<td><button class="btn-delete">删除</button></td>
					`;
					//<td><input type="number" class="taxAmount" min="0" step="0.01"></td>
					// 为税率输入框绑定input事件
					const bindTaxLvInputEvent = function () {
						const taxLvInputs = document.querySelectorAll('.taxLv');
						taxLvInputs.forEach(function (taxLvInput) {
							const howmanyInput = taxLvInput.closest('tr').querySelector('.howmany');
							const taxAmountInput = taxLvInput.closest('tr').querySelector('.taxAmount');
							taxLvInput.addEventListener('input', function () {
								const amount = parseFloat(howmanyInput.value) || 0;
								const taxRate = parseFloat(taxLvInput.value) / 100 || 0;
								taxAmountInput.value = (amount * taxRate).toFixed(2);
							});
						});
					};
					bindTaxLvInputEvent();
					// 新增物料行时也需要重新绑定事件
					document.getElementById('add-material-btn').addEventListener('click', function () {
						// 已有代码逻辑...
						bindTaxLvInputEvent();
					});
					//pcount数量
					//price单价
					//howmany金额
					//taxLv税率
					//taxAmount税额
					tbody.appendChild(newRow);

						// 绑定数量和单价输入框的input事件
						const pcountInput = newRow.querySelector('.pcount');
						const priceInput = newRow.querySelector('.price');
						const howmanyInput = newRow.querySelector('.howmany');
							pcountInput.addEventListener('input', function () {
								const quantity = parseFloat(pcountInput.value) || 0;
								const unitPrice = parseFloat(priceInput.value) || 0;
								howmanyInput.value = (quantity * unitPrice).toFixed(2);
							});
								 priceInput.addEventListener('input', function () {
									const quantity = parseFloat(pcountInput.value) || 0;
									const unitPrice = parseFloat(priceInput.value) || 0;
									howmanyInput.value = (quantity * unitPrice).toFixed(2);
								});

					// 绑定选择按钮事件
					newRow.querySelector('.btn-select').addEventListener('click', function() {
						// 明确使用window对象
						window.currentSelectingRow = {
							index: rowCount,
							element: newRow
						};
						console.log("设置当前选中行:", window.currentSelectingRow);
						openMaterialModal();
					});

					// 绑定删除按钮事件
					newRow.querySelector('.btn-delete').addEventListener('click', function() {
						tbody.removeChild(newRow);
						// 重新排序序号
						updateRowNumbers();
					});
				});

					// 打开物料选择模态框
					function openMaterialModal() {
						if (modal) {
							modal.style.display = 'block';
							loadMaterialData();
						} else {
							console.error('找不到模态框元素');
						}
					}

				// 关闭模态框
					 document.querySelector('.close')?.addEventListener('click', function() {
						if (modal) modal.style.display = 'none';
					});
				// 加载物料数据到选择表格
				function loadMaterialData(searchParams ={}) {
					const tbody = document.getElementById('material-select-tbody');
					tbody.innerHTML = '';

					// 构建查询参数
					const queryParams = new URLSearchParams();
					if (searchParams.material_code) queryParams.append('material_code', searchParams.material_code);
					if (searchParams.material_name) queryParams.append('material_name', searchParams.material_name);

					//---------------------------
					// 从服务器获取数据----http://localhost:5234/api改为了@ViewBag.BaseUrl/T7
					fetch(`@ViewBag.BaseUrl/T7/Materials/GetMaterial_Basic?${queryParams.toString()}`)
					.then(response => response.json())
					.then(data => {
						if (data.code === 0 && data.data) {
							// 清空表格
							//tbody.innerHTML = '';

							// 填充数据
							data.data.forEach(material => {
								const row = document.createElement('tr');
								row.innerHTML = `
									<td>${material.material_code}</td>
									<td>${material.material_name}</td>
									<td>${material.model_specification}</td>
									<td>${material.unit_of_measurement_name}</td>
									<td><button class="btn-choose">选择</button></td>
								`;

								// 绑定选择事件
								row.querySelector('.btn-choose').addEventListener('click', function() {
									selectMaterial(material);
									//console.log(material)
								});

								tbody.appendChild(row);
							});
						} else {
							console.error('获取物料数据失败:', data.msg);
						}
					})
					.catch(error => {
						console.error('获取物料数据出错:', error);
					});
				}

				// 选择物料
				function selectMaterial(material) {
					if (!window.currentSelectingRow?.element) {
						console.error('没有选中的行或元素不存在');
						return;
					}
					const row = window.currentSelectingRow.element;
					const inputs = {
						code: row.querySelector(".material-code"),
						name: row.querySelector(".material-name"),
						spec: row.querySelector(".specification"),
						unit: row.querySelector(".unit"),

						// 新增获取采购订单号、仓库、入库单号输入框元素
						orderNumber: row.querySelector(".order-number"),
						warehouse: row.querySelector(".warehouse"),
						receiptNumber: row.querySelector(".receipt-number")
					};
					console.log("当前行和输入元素:", {row, inputs});

					if (inputs.code && inputs.name && inputs.spec && inputs.unit) {
						inputs.code.value = material.material_code || '';
						inputs.name.value = material.material_name || '';
						inputs.spec.value = material.model_specification || '';
						inputs.unit.value = material.unit_of_measurement_name || '';
						// 为采购订单号、仓库、入库单号设置默认值
						if (inputs.orderNumber) inputs.orderNumber.value = '手工单据';
						if (inputs.warehouse) inputs.warehouse.value = '手工单据';
						if (inputs.receiptNumber) inputs.receiptNumber.value = '手工单据';


						// 触发输入事件
						Object.values(inputs).forEach(input => input.dispatchEvent(new Event('input')));
					}else {
						console.error('部分输入元素未找到');
					}
					if (modal) modal.style.display = 'none';
				}

				// 更新行号
				function updateRowNumbers() {
					const rows = document.querySelectorAll('#material-tbody tr');
					rows.forEach((row, index) => {
						row.cells[0].textContent = index + 1;
						row.dataset.index = index + 1;
					});
					rowCount = rows.length;
				}

				// 搜索功能
				document.getElementById('search-btn')?.addEventListener('click', function() {
					const searchInput = document.getElementById('material-search');
					if (searchInput) {
						const searchText = searchInput.value.trim();
						const searchParams = searchText ?
							(isNaN(searchText) ? { material_name: searchText } : { material_code: searchText })
							: {};
						loadMaterialData(searchParams);
					}
				});

		} )


		//---111
	</script>

	<!-- 操作列按钮模板 -->
	<script type="text/html" id="operationBar">
		<a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
		<a class="layui-btn layui-btn-success layui-btn-xs" lay-event="lookit">查看</a>
	</script>
</body>
</html>